package cn.iocoder.yudao.module.handguard.tool;

import cn.iocoder.yudao.module.handguard.controller.admin.productaccesspercentage.vo.PercentageVO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.product.ProductDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccess.ProductAccessDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccessitem.ProductAccessItemDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccesspercentage.ProductAccessPercentageDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable1.UserBaseTable1DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable10.UserBaseTable10DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable11.UserBaseTable11DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable12.UserBaseTable12DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable13.UserBaseTable13DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable14.UserBaseTable14DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable15.UserBaseTable15DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable16.UserBaseTable16DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable2.UserBaseTable2DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable3.UserBaseTable3DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable4.UserBaseTable4DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable5.UserBaseTable5DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable6.UserBaseTable6DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable7.UserBaseTable7DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable8.UserBaseTable8DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable9.UserBaseTable9DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.usertablesaudit.UserTablesAuditDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: liuweijun
 * @since: 2023/10/16 10:47
 * @description:
 */
@Slf4j
public class CalculateUtils {

    /**
     * 按揭房信贷
     *
     * @Description: 建筑面积*X成和Y成=2个额度
     */
    public static String calculateTable1(UserBaseTable1DO table1DO, ProductDO productDO) {
        // 建筑面积*X成和Y成=2个额度
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed =table1DO.getAreaOfStructure().multiply(productDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
        eds =table1DO.getAreaOfStructure().multiply(productDO.getPortionsTwo()).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    /**
     * 保单贷
     *
     * @Description:  年缴费合计*X倍和Y倍=2个额度
     */
    public static String calculateTable2(UserBaseTable2DO table2DO, ProductDO productDO) {
        // 年缴费合计*X倍和Y倍=2个额度
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed =table2DO.getAnnualPayment().multiply(productDO.getMultiple()).setScale(2, RoundingMode.HALF_UP);
        eds =table2DO.getAnnualPayment().multiply(productDO.getMultipleTwo()).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }

    /**
     * 个人贴息贷款
     *
     * @Description: 初始额度10-30万
     * 最高100万
     */
    public static String calculateTable3() {
        //BigDecimal max = new BigDecimal(300000);
        //BigDecimal min = new BigDecimal(100000);
        //BigDecimal amounts = new BigDecimal(0.0);
        //BigDecimal yearAmount = new BigDecimal(table2DO.getAnnualPayment());
        //amounts  = yearAmount.multiply(multiple);
        ////大于一百万则最高一百万
        //if (amounts.compareTo(max) == 1){
        //    return max;
        //}
        return "100000—300000";
    }


    /**
     * 工薪贷
     *
     * @Description: 年薪×X倍—负债=最低额度
     * 年薪×Y倍—负债=最高额度
     * 显示最低额度至最高额度
     */
    public static String calculateTable4(UserBaseTable4DO table4DO, ProductDO productDO) {
        //年薪
        BigDecimal annualSalary = table4DO.getAnnualSalary();
        //负债
        BigDecimal liabilities = table4DO.getLiabilities();

        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed = annualSalary.multiply(productDO.getMultiple()).subtract(liabilities).setScale(2, RoundingMode.HALF_UP);
        eds = annualSalary.multiply(productDO.getMultipleTwo()).subtract(liabilities).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }

    /**
     * 公积金贷
     *
     * @Description: 年缴费合计*X成和Y成=2个额度
     *
     */
    public static String calculateTable5(UserBaseTable5DO table5DO, ProductDO productDO) {
        //年缴费
        BigDecimal yearMoney = table5DO.getPolicyYearPayment();
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed = yearMoney.multiply(productDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
        eds = yearMoney.multiply(productDO.getPortionsTwo()).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }

    /**
     * 企业贴息贷款
     *
     * @Description: 人数*20万=额度
     */
    public static String calculateTable6(UserBaseTable6DO table6DO) {
        BigDecimal max = new BigDecimal(1000000);
        BigDecimal amounts = new BigDecimal(0.0);

        String number = table6DO.getConditions().replace("人", "");
        int num = Integer.valueOf(number);
        BigDecimal b = new BigDecimal(num);
        amounts = b.multiply(new BigDecimal(200000)).setScale(2, RoundingMode.HALF_UP);
        amounts = formatZeroMoney(amounts);
        return formatMoneyUnit(amounts);
    }


    /**
     * 全款车按揭车信贷
     * @Description:
     * 全款信贷额度：市场价*X成和Y成=2个额度
     * 按揭信贷额度：市场价*X成和Y成—按揭车剩余本金=2个额度
     */
    public static String calculateTable7(UserBaseTable7DO table7DO, ProductDO productDO) {
        BigDecimal ed = new BigDecimal(0.0);
        BigDecimal eds = new BigDecimal(0.0);
        String carType = table7DO.getCarPower();
        String amounts = "";
        if (carType.equals("抵押") && !table7DO.getCarState().equals("按揭")) {
            ed = table7DO.getTotalPayment().multiply(productDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
            eds = table7DO.getTotalPayment().multiply(productDO.getPortionsTwo()).setScale(2, RoundingMode.HALF_UP);
            ed = formatZeroMoney(ed);
            eds = formatZeroMoney(eds);
            amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        }else {
            ed = table7DO.getTotalPayment().multiply(productDO.getPortions()).subtract(table7DO.getOddCorpus()).setScale(2, RoundingMode.HALF_UP);
            eds = table7DO.getTotalPayment().multiply(productDO.getPortionsTwo()).subtract(table7DO.getOddCorpus()).setScale(2, RoundingMode.HALF_UP);
            ed = formatZeroMoney(ed);
            eds = formatZeroMoney(eds);
            amounts = formatMoneyUnit(ed)+ "—" + formatMoneyUnit(eds);
        }
        return amounts;
    }

    /**
     * 商业商住楼写字楼厂房一抵押
     *
     * @Description: 租金单价×建筑面积×Z倍×（X成和Y成）=2个额度
     */
    public static String calculateTable8(UserBaseTable8DO table8DO, ProductDO productDO) {
        //租金单价
        BigDecimal rent = table8DO.getRent();
        //租金单价*建筑面积*Z倍*（X成）=额度
        //租金单价*建筑面积*Z倍*（Y成）=额度
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed = rent.multiply(new BigDecimal(table8DO.getAreaOfStructure())).multiply(productDO.getMultiple()).multiply(productDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
        eds = rent.multiply(new BigDecimal(table8DO.getAreaOfStructure())).multiply(productDO.getMultiple()).multiply(productDO.getPortionsTwo()).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    /**
     * 商业商住楼写字楼二次抵押
     *
     * @Description: 租金单价*建筑面积*Z倍*X成-剩余本金=最低额度
     * 租金单价*建筑面积*Z倍*Y成-剩余本金=最高额度
     */
    public static String calculateTable9(UserBaseTable9DO table9DO, ProductDO productDO) {
        //租金单价
        BigDecimal rent = table9DO.getRent();
        //租金单价*建筑面积*Z倍*（X成）-剩余本金 = 额度
        //租金单价*建筑面积*Z倍*（Y成）-剩余本金 = 额度
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed = rent.multiply(new BigDecimal(table9DO.getAreaOfStructure())).multiply(productDO.getMultiple()).multiply(productDO.getPortions()).subtract(table9DO.getOddCorpus()).setScale(2, RoundingMode.HALF_UP);
        eds = rent.multiply(new BigDecimal(table9DO.getAreaOfStructure())).multiply(productDO.getMultiple()).multiply(productDO.getPortionsTwo()).subtract(table9DO.getOddCorpus()).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    /**
     * 商业写字楼按揭贷款
     * 首套：租金单价*建筑面积*Z倍*（X成和Y成）=2个额度
     * 二套：租金单价*建筑面积*Z倍*（X1成和Y1成）=2个额度
     */
    public static String calculateTable10(UserBaseTable10DO table10DO, ProductDO productDO) {
        //租金单价
        BigDecimal rent = table10DO.getRent();
        //首套：租金单价*建筑面积*Z倍*（X成和Y成）=2个额度
        //二套：租金单价*建筑面积*Z倍*（X1成和Y1成）=2个额度
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        if (table10DO.getOneOrTwo().equals("首套")){
            ed = rent.multiply(new BigDecimal(table10DO.getAreaOfStructure())).multiply(productDO.getMultiple()).multiply(productDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
            eds = rent.multiply(new BigDecimal(table10DO.getAreaOfStructure())).multiply(productDO.getMultiple()).multiply(productDO.getPortionsTwo()).setScale(2, RoundingMode.HALF_UP);
        }else {
            ed = rent.multiply(new BigDecimal(table10DO.getAreaOfStructure())).multiply(productDO.getPortions()).multiply(productDO.getAlternativePortionsOne()).setScale(2, RoundingMode.HALF_UP);
            eds = rent.multiply(new BigDecimal(table10DO.getAreaOfStructure())).multiply(productDO.getPortions()).multiply(productDO.getAlternativePortionsTwo()).setScale(2, RoundingMode.HALF_UP);
        }
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    /**
     * 税贷
     *
     * @Description:  近一年纳税总金额*X倍和Y倍—整体负债=2个额度
     */
    public static String calculateTable11(UserBaseTable11DO table11DO,ProductDO productDO) {
        //近一年纳税总金额
        BigDecimal zje = table11DO.getGrossTaxContribution();
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed = zje.multiply(productDO.getMultiple()).subtract(table11DO.getLiabilities()).setScale(2, RoundingMode.HALF_UP);
        eds = zje.multiply(productDO.getMultipleTwo()).subtract(table11DO.getLiabilities()).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    /**
     * 企业流水贷
     *
     * @Description:
     * 年经营流水*X—整体负债=最低额度
     * 年经营流水*Y—整体负债=最高额度
     * 显示最低额度至最高额度
     */
    public static String calculateTable12(UserBaseTable12DO table12DO, ProductDO productDO) {
        BigDecimal runningWater = table12DO.getRunningWater();
        BigDecimal creditLiability = table12DO.getCreditLiability();

        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed = runningWater.multiply(productDO.getMultiple()).subtract(creditLiability).setScale(2, RoundingMode.HALF_UP);
        eds = runningWater.multiply(productDO.getMultipleTwo()).subtract(creditLiability).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    /**
     * 企业发票贷
     *
     * @Description:
     * 企业年开票金额*X—整体负债=最低额度
     * 企业年开票金额*Y—整体负债=最高额度
     * 显示最低额度至最高额度
     */
    public static String calculateTable13(UserBaseTable13DO table13DO, ProductDO productDO) {
        BigDecimal yearAmount = table13DO.getYearAmount();
        BigDecimal liabilities = table13DO.getLiabilities();

        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        ed = yearAmount.multiply(productDO.getMultiple()).subtract(liabilities).setScale(2, RoundingMode.HALF_UP);
        eds = yearAmount.multiply(productDO.getMultipleTwo()).subtract(liabilities).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    /**
     * 住宅按揭贷款
     * 首套：评估价*建筑面积*（X成和Y成）=2个额度
     * 二套：评估价*建筑面积*（X1成和Y1成）=2个额度
     */
    public static String calculateTable14(UserBaseTable14DO table14DO, ProductDO productDO) {
        //首套：评估价*建筑面积*（X成和Y成）=2个额度
        //二套：评估价*建筑面积*（X1成和Y1成）=2个额度
        //租金单价
        BigDecimal pgj = table14DO.getValuationPrice();
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        if (table14DO.getOneOrTwo().equals("首套")){
            ed = pgj.multiply(new BigDecimal(table14DO.getAreaOfStructure())).multiply(productDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
            eds = pgj.multiply(new BigDecimal(table14DO.getAreaOfStructure())).multiply(productDO.getPortionsTwo()).setScale(2, RoundingMode.HALF_UP);
        }else {
            ed = pgj.multiply(new BigDecimal(table14DO.getAreaOfStructure())).multiply(productDO.getAlternativePortionsOne()).setScale(2, RoundingMode.HALF_UP);
            eds = pgj.multiply(new BigDecimal(table14DO.getAreaOfStructure())).multiply(productDO.getAlternativePortionsTwo()).setScale(2, RoundingMode.HALF_UP);
        }
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }

    /**
     * 住宅抵押
     * 评估价*建筑面积*X成和Y成=X~Y的范围额度
     */
    public static String calculateTable15(UserBaseTable15DO table15DO, ProductDO productDO) {
        BigDecimal amount = table15DO.getValuationPrice();
        BigDecimal areaOfStructure = new BigDecimal(table15DO.getAreaOfStructure());
        BigDecimal ed = amount.multiply(areaOfStructure).multiply(productDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
        BigDecimal eds = amount.multiply(areaOfStructure).multiply(productDO.getPortionsTwo()).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    /**
     * 住宅二次抵押
     * 评估价*建筑面积*X成-剩余本金=最低范围额度
     * 评估价*建筑面积*Y成-剩余本金=最高范围额度
     */
    public static String calculateTable16(UserBaseTable16DO table16DO, ProductDO productDO) {
        //评估价*建筑面积*X成-剩余本金=最低范围额度
        //评估价*建筑面积*Y成-剩余本金=最高范围额度
        BigDecimal amount = table16DO.getValuationPrice();
        BigDecimal areaOfStructure = new BigDecimal(table16DO.getAreaOfStructure());
        BigDecimal ed = amount.multiply(areaOfStructure).multiply(productDO.getPortions()).subtract(table16DO.getOddCorpus()).setScale(2, RoundingMode.HALF_UP);
        BigDecimal eds = amount.multiply(areaOfStructure).multiply(productDO.getPortionsTwo()).subtract(table16DO.getOddCorpus()).setScale(2, RoundingMode.HALF_UP);
        ed = formatZeroMoney(ed);
        eds = formatZeroMoney(eds);
        String amounts = formatMoneyUnit(ed)+ "—" +formatMoneyUnit(eds);
        return amounts;
    }


    //==================================================================准入匹配月供计算

    /**
     * 先息后本：预估额度×年华利率÷12个月就等于贷款月供。
     * 等额本息：（预估额度÷还款周期）+（预估额度×年华利率÷12个月）＝贷款月供
     * 等额本金：（预估额度÷还款周期）+（预估额度×年华利率÷12个月）＝贷款月供
     */
    public static ArrayList<BigDecimal> getMonthCalculation(ProductAccessDO accessDO, String amount,Integer age) {
        ArrayList <BigDecimal> mArr = new ArrayList<>();
        BigDecimal m = new BigDecimal(BigInteger.ZERO);
        if (accessDO.getPublicityTypeId() == 1l) { //完成按揭房信贷公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 2l) { //完成保单贷公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 3l) { //完成个人贴息贷款公式表
            //mArr = getCommCalculateOddMethod(accessDO, amount);
        } else if (accessDO.getPublicityTypeId() == 4l) { //完成工薪贷公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 5l) {  //完成公积金贷公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 6l) { //完成企业贴息贷款公式表
            //mArr = getCommCalculateOddMethod(accessDO, amount);
        } else if (accessDO.getPublicityTypeId() == 7l) {//完成全款车按揭车信贷公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 8l) { //完成商业商住楼写字楼厂房一抵押公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 9l) { //完成商业商住楼写字楼二次抵押公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 10l) { //完成商业写字楼按揭贷款公式
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 11l) { //完成税贷公示表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 12l) { //完成企业流水贷公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 13l) { //完成企业发票贷公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 14l) { //完成住宅按揭贷款公式
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 15l) { // 完成住宅抵押公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        } else if (accessDO.getPublicityTypeId() == 16l) { //完成住宅二次抵押公式表
            mArr = getCommCalculateCotMethod(accessDO, amount,age, accessDO.getPublicityTypeId());
        }
        return mArr;
    }


    public static ArrayList<BigDecimal>  getCommCalculateOddMethod(ProductAccessDO accessDO, String amount) {
        ArrayList<BigDecimal>  mArr = new ArrayList<>();
        BigDecimal m = new BigDecimal(BigInteger.ZERO);
        BigDecimal ed = new BigDecimal(amount);
        //月供 = 额度*年华/12=月供
        if (accessDO.getModeOfRepayment().equals("先息后本")) {
            m = ed.multiply(accessDO.getTimeRate()).divide(new BigDecimal(12), RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
        } else if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")) {
            BigDecimal edd = ed.multiply(accessDO.getTimeRate()).divide(new BigDecimal(12)).setScale(2, RoundingMode.HALF_UP);
            m = ed.divide(BigDecimal.valueOf(accessDO.getDeadline())).add(edd).setScale(2, RoundingMode.HALF_UP);
        }
        //m = formatZeroMoney(m);
        mArr.add(m);
        return mArr;
    }

    public static ArrayList <BigDecimal> getCommCalculateBothMethod(ProductAccessDO accessDO, String amount) {
        ArrayList <BigDecimal> mArr = new ArrayList<>();
        String[] arr = amount.split("—");
        for (int i = 0; i < arr.length; i++) {
            BigDecimal m = new BigDecimal(BigInteger.ZERO);
            BigDecimal ed = new BigDecimal(arr[i].replace(",",""));
            if (accessDO.getModeOfRepayment().equals("先息后本")) {
                BigDecimal rate = accessDO.getTimeRate().divide(new BigDecimal(100));
                m = ed.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
            } else if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")) {
                BigDecimal rate = accessDO.getTimeRate().divide(new BigDecimal(100));
                BigDecimal edd = ed.multiply(rate).divide(new BigDecimal(12)).setScale(2, RoundingMode.HALF_UP);
                m = ed.divide(BigDecimal.valueOf(accessDO.getDeadline())).add(edd).setScale(2, RoundingMode.HALF_UP);
            }
            //m = formatZeroMoney(m);
            mArr.add(m);

        }
        return mArr;
    }

    public static ArrayList<BigDecimal>  getCommCalculateCotMethod(ProductAccessDO accessDO, String amount,Integer userAge,Long typeId) {
        ArrayList <BigDecimal> mArr = new ArrayList<>();
        BigDecimal e = new BigDecimal(BigInteger.ZERO);
        BigDecimal ed = new BigDecimal(BigInteger.ZERO);
        BigDecimal eds = new BigDecimal(BigInteger.ZERO);
        BigDecimal rate = accessDO.getTimeRate().divide(new BigDecimal(100));
        BigDecimal money = new BigDecimal(amount);
        if (typeId == 1l){
            if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")){
                // 等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                ed = money.divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
                e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            } else if (accessDO.getModeOfRepayment().equals("先息后本")) {
                // 先息后本=预估额度×年化利率÷还款周期=月供
                ed = money.multiply(rate).divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                e = ed.setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            }
        } else  if (typeId == 2l){
            if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")){
                // 等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                ed = money.divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
                e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            } else if (accessDO.getModeOfRepayment().equals("先息后本")) {
                // 先息后本=预估额度×年化利率÷还款周期=月供
                ed = money.multiply(rate).divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                e = ed.setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            }
        }else if (typeId == 4l){
            if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")){
                // 等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                ed = money.divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
                e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            } else if (accessDO.getModeOfRepayment().equals("先息后本")) {
                //先息后本=预估额度×年化利率÷还款周期=月供
                ed = money.multiply(rate).divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                e = ed.setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            }
        }else if (typeId == 5l){
            if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")){
                // 等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                ed = money.divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
                e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            } else if (accessDO.getModeOfRepayment().equals("先息后本")) {
                //先息后本=预估额度×年化利率÷还款周期=月供
                ed = money.multiply(rate).divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                e = ed.setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            }
        }else if (typeId == 7l){
            if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")){
                // 等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                ed = money.divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
                e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            } else if (accessDO.getModeOfRepayment().equals("先息后本")) {
                //先息后本=预估额度×年化利率÷还款周期=月供
                ed = money.multiply(rate).divide(new BigDecimal(accessDO.getDeadline()), RoundingMode.HALF_UP);
                e = ed.setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            }
        }else if (typeId == 8l || typeId == 9l) { //商业一抵
            //等额本金，等额本息：额度/（70-客户年龄）+（额度*年华利率/12）=月供
            //先息后本：额度*年华利率/12=月供
            if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")){
                int a = 70;
                int b = userAge.intValue();
                int age = a-b;
                ed = money.divide(new BigDecimal(age), RoundingMode.HALF_UP);
                eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
                e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            } else if (accessDO.getModeOfRepayment().equals("先息后本")) {
                e = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
                //e = eds.setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            }
        } else if (typeId == 10l) { //商业按揭
            //额度/（80-客户年龄）+（额度*年华利率/12）=月供
            int a = 80;
            int b = userAge.intValue();
            int age = a-b;
            ed = money.divide(new BigDecimal(age), RoundingMode.HALF_UP);
            eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
            e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
            mArr.add(e);
        } else if (typeId == 11l) { //企业税贷
            //额度*年华利率/12=月供
            e = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
            mArr.add(e);
        } else if (typeId == 12l) { //企业流水贷
            //额度*年华利率/12=月供
            e = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
            mArr.add(e);
        } else if (typeId == 13l) { //企业发票贷
            //额度*年华利率/12=月供
            e = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
            mArr.add(e);
        } else if (typeId == 14l){ //住宅按揭贷款
            //额度/（70-客户年龄）+（额度*年华利率/12）=月供
            int a = 70;
            int b = userAge.intValue();
            int age = a-b;
            ed = money.divide(new BigDecimal(age), RoundingMode.HALF_UP);
            eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
            e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
            mArr.add(e);
        }else if (typeId == 15l){
            //额度*年华利率/12=月供
            e = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);;
            mArr.add(e);
        }else if (typeId == 16l){ //住宅二次抵押
           // 等额本金，等额本息：额度/（70-客户年龄）+（额度*年华利率/12）=月供
           // 先息后本：额度*年华利率/12=月供
            if (accessDO.getModeOfRepayment().equals("等额本金") || accessDO.getModeOfRepayment().equals("等额本息")){
                int a = 70;
                int b = userAge.intValue();
                int age = a-b;
                ed = money.divide(new BigDecimal(age), RoundingMode.HALF_UP);
                eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP);
                e = ed.add(eds).setScale(2, RoundingMode.HALF_UP);
                mArr.add(e);
            } else if (accessDO.getModeOfRepayment().equals("先息后本")) {
                eds = money.multiply(rate).divide(new BigDecimal(12), RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
                mArr.add(eds);
            }
        }
        return mArr;
    }


    //======================================产品准入校验项
    public static Boolean getProductCheck(List<ProductAccessItemDO> itemList, List<UserTablesAuditDO> lists, String bank,String productName) {
        boolean flag = true;
        //嵌套循环对比项
        endLoop:
        for (ProductAccessItemDO item1 : itemList) {
            UserTablesAuditDO item2 = lists.stream().filter(l -> item1.getPid().equals(l.getPid())).findFirst().orElse(null);
            //业务员提交对应资料是否存在、产品准入数据项中
            if (StringUtils.isEmpty(item1.getResultValue()) && !item1.getCategory().equals("301")) {  //空的的项跳过
            } else {
                if (item1.getResultValue().contains("不限")) {

                } else if (item1.getCategory().equals("200")) {
                    if (!DataConversionUtils.getCommonCheck200(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项200-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("201")) {
                    if (!DataConversionUtils.getCommonCheck201(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项201-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "”数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("202")) {
                    if (!DataConversionUtils.getCommonCheck202(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项202-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "”数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("203")) {
                    if (!DataConversionUtils.getCommonCheck203(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项203-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "”数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("204")) {
                    if (!DataConversionUtils.getCommonCheck204(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项204-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "”数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("205")) {
                    if (!DataConversionUtils.getCommonCheck205(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项205-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "”数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("206")) {
                    if (!DataConversionUtils.getCommonCheck206(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项206-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "”数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("207")) {
                    if (!DataConversionUtils.getCommonCheck207(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项207-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "”数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("208")) {
                    if (!DataConversionUtils.getCommonCheck208(item1.getResultValue(), item2.getResultValue())) {
                        log.info(productName+"-准入项208-" + item1.getClassName() + "：数据1：" + item1.getResultValue() + "”数据2：" + item2.getResultValue() + "====不匹配");
                        flag = false;
                        break endLoop;
                    }
                } else if (item1.getCategory().equals("301")) {
                    //查询银行机构
                    if (StringUtils.isNotEmpty(item2.getResultValue()) && StringUtils.isNotEmpty(bank)) {
                        if (item2.getResultValue().contains(bank)) {
                            flag = false;
                            log.info(productName+"-准入项301-" + "：数据2：" + item2.getResultValue() + "存在排除银行机构");
                            break endLoop;
                        }
                    }
                }
            }
        }
        return flag;
    }

    //格式化千单位为0
    public static BigDecimal formatZeroMoney(BigDecimal m){
        BigDecimal zero = new BigDecimal(BigInteger.ZERO);
        if (m.compareTo(zero) == 0 ){
            return zero;
        }else if (m.compareTo(BigDecimal.ZERO) < 0) {
            return zero;
        }else {
            String str = m.toString();
            if (str.contains(".")){
                str = removeAfterDot(str);
            }
            if (str.length() > 4) {
                String replaced =  str.substring(0, str.length() - 3) + "000"; // 拼接前面部分和3个0
                BigDecimal amount = new BigDecimal(replaced);
                return amount;
            }else {
                return m;
            }
        }

    }

    public static String removeAfterDot(String str) {
        // 使用split方法分割字符串，在点号处分割
        String[] parts = str.split("\\.", 2);
        // 返回分割后的第一部分
        return parts[0];
    }


    /**===================================提成计算公共方法========================================**/
    public static PercentageVO getDeduct(ProductAccessPercentageDO percentageDO,BigDecimal quotaFormula){
        PercentageVO percentageVO = new PercentageVO();
        if (percentageDO.getDeductType().equals("0")){ //数值直接显示
            BeanUtils.copyProperties(percentageDO,percentageVO);

            //总利润
            BigDecimal grossProfit = new BigDecimal(BigInteger.ZERO);
            grossProfit = percentageVO.getDirectProfit().add(percentageVO.getIndirectProfit()).setScale(2, RoundingMode.HALF_UP);;
            percentageVO.setGrossProfit(grossProfit);

            //平台利润统计=当日成交放款后的产品的总利润-区域经理提成-业务主管提成-业务经理提成-权证主管提成-权证提成
            BigDecimal platformProfit = new BigDecimal(BigInteger.ZERO);
            platformProfit =percentageVO.getGrossProfit().subtract(percentageVO.getRegionalManagerRoyalty())
                    .subtract(percentageVO.getBusinessSupervisorRoyalty()).subtract(percentageVO.getBusinessManagerRoyalty())
                    .subtract(percentageVO.getWarrantSupervisor()).subtract(percentageVO.getWarrantOfficer());
            percentageVO.setPlatformProfit(platformProfit);

        }else if (percentageDO.getDeductType().equals("1")){ //比分比计算

            //直接利润
            BigDecimal zlr = new BigDecimal(BigInteger.ZERO);
            zlr = quotaFormula.multiply(percentageDO.getDirectProfit().divide(new BigDecimal(100)));
            percentageVO.setDirectProfit(zlr);

            //间接利润
            BigDecimal jlr = new BigDecimal(BigInteger.ZERO);
            jlr = quotaFormula.multiply(percentageDO.getIndirectProfit().divide(new BigDecimal(100)));
            percentageVO.setIndirectProfit(jlr);

            //总利润
            BigDecimal grossProfit = new BigDecimal(BigInteger.ZERO);
            grossProfit = zlr.add(jlr).setScale(2, RoundingMode.HALF_UP);;
            percentageVO.setGrossProfit(grossProfit);

            //区域经理提成
            BigDecimal regionalManagerRoyalty = new BigDecimal(BigInteger.ZERO);
            regionalManagerRoyalty = grossProfit.multiply(percentageDO.getRegionalManagerRoyalty().divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP);;
            percentageVO.setRegionalManagerRoyalty(regionalManagerRoyalty);

            //业务主管提成
            BigDecimal businessSupervisorRoyalty = new BigDecimal(BigInteger.ZERO);
            businessSupervisorRoyalty = grossProfit.multiply(percentageDO.getBusinessSupervisorRoyalty().divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP);;
            percentageVO.setBusinessSupervisorRoyalty(businessSupervisorRoyalty);

            //业务经理提成
            BigDecimal businessManagerRoyalty = new BigDecimal(BigInteger.ZERO);
            businessManagerRoyalty = grossProfit.multiply(percentageDO.getBusinessManagerRoyalty().divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP);;
            percentageVO.setBusinessManagerRoyalty(businessManagerRoyalty);

            //权证主管提成
            BigDecimal warrantSupervisor = new BigDecimal(BigInteger.ZERO);
            warrantSupervisor = grossProfit.multiply(percentageDO.getWarrantSupervisor().divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP);;
            percentageVO.setWarrantSupervisor(warrantSupervisor);

            //权证员提成
            percentageVO.setWarrantOfficer(percentageDO.getWarrantOfficer());

            //推荐人财富值返利
            BigDecimal referrerRoyalty = new BigDecimal(BigInteger.ZERO);
            referrerRoyalty = grossProfit.multiply(percentageDO.getReferrerRoyalty().divide(new BigDecimal(100)));
            percentageVO.setReferrerRoyalty(referrerRoyalty);

            //客户财富值返利
            BigDecimal clientRoyalty = new BigDecimal(BigInteger.ZERO);
            clientRoyalty = grossProfit.multiply(percentageDO.getClientRoyalty().divide(new BigDecimal(100)));
            percentageVO.setClientRoyalty(clientRoyalty);


            //平台利润统计=当日成交放款后的产品的总利润-区域经理提成-业务主管提成-业务经理提成-权证主管提成-权证提成
            BigDecimal platformProfit = new BigDecimal(BigInteger.ZERO);
            platformProfit =percentageVO.getGrossProfit().subtract(percentageVO.getRegionalManagerRoyalty())
                    .subtract(percentageVO.getBusinessSupervisorRoyalty()).subtract(percentageVO.getBusinessManagerRoyalty())
                    .subtract(percentageVO.getWarrantSupervisor()).subtract(percentageVO.getWarrantOfficer());
            percentageVO.setPlatformProfit(platformProfit);

        }
        return percentageVO;
    }



    public static String formatMoneyUnit(BigDecimal m){
        NumberFormat format = NumberFormat.getInstance();
        //设置小数部分的最大位数
        // format.setMaximumFractionDigits(2);
        //设置小数部分的最小位数
        //format.setMinimumFractionDigits(2);
        //设置是否使用千位分隔符
        format.setGroupingUsed(true);
        //设置货币符号
        //format.setCurrency(Currency.getInstance(Locale))
        String formattedAmount = format.format(m);
        return formattedAmount;
    }






    public static void main(String[] args) {
         BigDecimal amount = new BigDecimal(1000001);
        BigDecimal max = null;
       // System.out.println(checkAmount(amount,max));
    }



//    public static void main(String[] args) {
//        int num = 0;
//        if (1==1){
//            num +=1;
//        }
//        if (1==1){
//            num +=1;
//        }
//        System.out.println("接口"+num);
//    }

}

